﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tomahawk.Runtime.Timeline
{
    public class ColorFilterEffectTrack : SpriteEffectTrack
    {
        public enum FilterTypes
        {
            None = 0,
            Grayscale = 1,
            Sepia = 2
        }

        [XmlElement("BrightnessLevel")]
        public string brightnessLevel = "";

        [XmlElement("ContrastLevel")]
        public string contrastLevel = "";

        [XmlElement("FilterType")]
        public FilterTypes filterType = FilterTypes.None;

        [XmlElement("FilterLevel")]
        public string filterLevel = "";

        [XmlElement("DefaultBrightness")]
        public float defaultBrightness = 0.0f;

        [XmlElement("DefaultContrast")]
        public float defaultContrast = 1.0f;

        [XmlElement("DefaultFilterLevel")]
        public float defaultFilter = 1.0f;
        
        private float brightness = 0.0f;
        private float contrast = 0.0f;
        private float filter = 0.0f;
        private Curve curveBrightness = new Curve();
        private Curve curveContrast = new Curve();
        private Curve curveFilter = new Curve();

        public ColorFilterEffectTrack() : base() { }

        public ColorFilterEffectTrack(string name) : base(name) { }

        protected override string GetEffectFile()
        {
            return @"Tomahawk.Content\SpriteEffects\ColorFilterEffect";
        }

        protected override void OnLoadEffectParameters(Effect effect)
        {
            effect.Parameters["Filter"].SetValue((int)filterType);
            effect.Parameters["Contrast"].SetValue(contrast);
            effect.Parameters["Brightness"].SetValue(brightness);
            effect.Parameters["FilterLevel"].SetValue(filter);
        }

        protected override bool OnLoad(GraphicsDevice graphics, ContentManager contentManager)
        {
            curveBrightness = LoadCurve(contentManager, brightnessLevel);
            curveContrast = LoadCurve(contentManager, contrastLevel);
            curveFilter = LoadCurve(contentManager, filterLevel);
            return base.OnLoad(graphics, contentManager);
        }

        public override void SortKeys() { }

        public override bool Update(float time)
        {
            brightness = curveBrightness != null ? curveBrightness.Evaluate(time) : defaultBrightness;
            contrast = curveContrast != null ? curveContrast.Evaluate(time) : defaultContrast;
            filter = curveFilter != null ? curveFilter.Evaluate(time) : defaultFilter;

            return true;
        }
    }
}
